<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                              |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: anguolei@clcw.com.cn                                           |
// +------------------------------------------------------------------------+
//

namespace AuctionCore\Cashier;


use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\CarDealer\AssetCenter;
use AuctionCore\CarResource\BreachCar;
use AuctionCore\CarResource\Car;
use AuctionCore\CarResource\CarCheck;
use AuctionCore\CarResource\SelfReceiveCar;
use AuctionCore\ChangeOrder\ChangeOrder;
use AuctionCore\System\SystemLog;
use AuctionCore\Other\Inbox;
use Think\Log;

class Collection extends Cashier
{
    protected $collection_id = null;
    public static $statusGroup = [
        'ORDER' => [1, 2, 3, 4],
        'CHANGE' => [6, 7, 8, 10],
        'RECHARGE' => 5,
        'MAINTENANCE' => 9,
    ];

    public function __construct($collection_id)
    {
        $this->model = M("collection");
        $this->collection_id = intval($collection_id);
    }

    /**
     * 新增收款信息
     * @param array $data
     * @return mixed
     */
    public static function add($data)
    {
        $collection_no = genBillsNo("SK", $data['payment_type']);
        $data['collection_no'] = $collection_no;
        return M("collection")->add($data);
    }

    /**
     * 添加拍单收款关系表
     * @param $order_id
     * @param $payment_type
     * @param $payment_method
     * @param $amount
     * @param $create_time
     * @return bool|mixed
     */
    public function addOrderCollection($order_id, $payment_type, $payment_method, $amount, $create_time)
    {
        if (intval($order_id) < 1 || $payment_type < 1 || $payment_method < 1) return false;
        $collection_id = self::add($payment_type, $payment_method, $amount, $create_time);
        if ($collection_id < 1) return false;
        $data = [
            'order_id' => $order_id,
            'collection_id' => $collection_id,
            'create_time' => $create_time
        ];
        return M("order_collections")->add($data);
    }

    /**
     * 获取收款信息
     * @return bool|mixed
     */
    public function getInfo()
    {
        if (intval($this->collection_id) < 1) return false;
        return $this->model->where(['id' => $this->collection_id])->find();
    }

    /**
     * 通过ID更新收款信息
     *
     * @param array $data
     * @return bool
     */
    public function update($data = array())
    {
        if ($this->collection_id < 1) return false;
        return $this->model->where(['id' => $this->collection_id])->save($data);
    }

    /**
     * 锁定收款单
     * @param int $id
     * @param int $emp_id
     * @param string $emp_name
     * @return bool
     */
    public static function lock($id, $emp_id = 0, $emp_name = '系统')
    {
        if (intval($id) < 1) return false;
        $info = self::getInfoById($id);
        if (empty($info)) return false;
        if ($info['status'] == 1) {
            $res = true;
        } elseif ($info['status'] == 2 || $info['status'] == 3) {
            $res = false;
        } else {
            $data = [];
            $data['status'] = 2;
            $data['emp_id'] = $emp_id;
            $data['emp_name'] = $emp_name;
            $data['update_time'] = date('Y-m-d H:i:s');
            $res = M("collection")->where(['id' => $id])->save($data);
        }
        return $res;
    }

    /**
     * 解锁收款单
     * @param $id
     * @param int $emp_id
     * @param string $emp_name
     * @return bool
     */
    public static function unlock($id, $emp_id = 0, $emp_name = '系统')
    {
        if (intval($id) < 1) return false;
        $info = self::getInfoById($id);
        if (empty($info)) return false;
        if ($info['status'] == 1) {
            $res = true;
        } elseif ($info['status'] == 0 || $info['status'] == 3) {
            $res = false;
        } else {
            $data = [
                'status' => 0,
                'emp_id' => $emp_id,
                'emp_name' => $emp_name,
                'update_time' => date('Y-m-d H:i:s'),
            ];
            $res = M("collection")->where(['id' => $id])->save($data);
        }
        return $res;
    }

    /**
     * 作废收款单
     * @param $id
     * @return bool
     */
    public static function invalid($id)
    {
        if (intval($id) < 1) return false;
        if (intval($id) < 1) return false;
        $info = self::getInfoById($id);
        if (empty($info)) return false;
        if ($info['status'] == 0 || $info['status'] == 2) {
            return M('collection')->where(['id' => $id])->save(['status' => 3]);
        } else {
            return false;
        }

    }

    /**
     * 获取收款单(复数)实收金额
     * @param array $ids
     * @return array|bool
     */
    public static function getCollectionByIds($ids = array())
    {
        if (empty($ids)) return false;
        $map = [];
        $map['id'] = ['in', $ids];
        $map['status'] = 1;
        $Collection = M('collection');
        $sumAmount = $Collection->where($map)->sum('amount');
        $data = [];
        $data['amount'] = $sumAmount;
        $data['status'] = $sumAmount > 0 ? 1 : 0;
        return $data;
    }

    /**
     * 收款列表
     * @param int $page
     * @param int $limit
     * @param array $params
     * @return array
     */
    public static function getList($page = 1, $limit = 10, $params = array())
    {
        $data = [];
        $page = intval($page) > 0 ? intval($page) : 1;
        $limit = intval($limit) > 0 ? intval($limit) : 10;
        $order = $params['status'] == 0 ? "create_time ASC" : "update_time DESC";

        $map = [];
        $map['status'] = intval($params['status']);
        //收款单号
        if (!empty($params['collection_no'])) {
            $map['collection_no'] = trim($params['collection_no']);
        }
        //收款类型
        if (!empty($params['payment_type'])) {
            $map['payment_type'] = intval($params['payment_type']);
        }
        $collection_ids = [];
        //车辆编号
        if (!empty($params['car_no'])) {
            $collection_ids = self::getCollectionIdsByCarSourceNu($params['car_no']);
            if (empty($collection_ids)) {
                return $data;
            }
        }
        $collection_ids = array_filter(array_unique($collection_ids));
        if (!empty($collection_ids)) {
            $map['id'] = ['in', $collection_ids];
        }
        //起止时间
        if (!empty($params['start_time']) || !empty($params['end_time'])) {
            if (empty($params['start_time'])) {
                $map['create_time'] = array("elt", $params['start_time'] . " 23:59:59");
            } elseif (empty($params['end_time'])) {
                $map['create_time'] = array("gt", $params['end_time'] . " 00:00:00");
            } else {
                $map['create_time'] = array(
                    array("gt", $params['start_time'] . " 00:00:00"),
                    array("elt", $params['end_time'] . " 23:59:59")
                );
            }
        }
        //分公司
        if ($params['branch_id'] > -1) {
            $map['branch_id'] = intval($params['branch_id']);
        }
        $m = M("collection");
        $total = $m->where($map)->count();
        $list = $m->where($map)->page($page)->limit($limit)->order($order)->select();
        if (!empty($list)) {
            foreach ($list as $key => $item) {
                if (in_array($item['payment_type'], self::$statusGroup['ORDER'])) {  //拍单相关
                    $data = self::getOrderInfoById($item['id']);
                    $list[$key]['order_no'] = $data['order_no'];
                    $list[$key]['car_source_nu'] = $data['sno'];
                    $list[$key]['account_type'] = "车商";
                    $list[$key]['account_name'] = $data['dealer_name'];
                    $list[$key]['account_id'] = $data['success_dealer_id'];
                    //其他渠道成交
                    if ($data['is_other_channel_deal'] == 1) {
                        if ($item['refer'] == 1) {
                            //违约车辆的
                            $carBackInfo = BreachCar::getInfoByOtherOrderId($data['order_id']);
                            $list[$key]['account_name'] = $carBackInfo['dealer_name'];
                        } elseif ($item['refer'] == 2) {
                            //自收车辆
                            $carBackInfo = SelfReceiveCar::getInfoByOtherOrderId($data['order_id']);
                            $list[$key]['account_name'] = $carBackInfo['dealer_name'];
                        }
                        $list[$key]['account_id'] = "--";
                    }

                } elseif (in_array($item['payment_type'], self::$statusGroup['CHANGE'])) { //变更单
                    if ($item['refer'] > 0) {
                        $isDefault = $item['payment_type'] == 8 ? 0 : 1;
                        $data = self::getRefundCarInfoByCollectionId($item['id'], $isDefault);
                    } else {
                        $data = self::getChangeInfoById($item['id']);
                    }
                    if ($item['payment_type'] == 6 || $item['payment_type'] == 10) {
                        $list[$key]['account_id'] = $data['success_dealer_id'];
                        $list[$key]['account_name'] = $data['dealer_name'];
                        $list[$key]['account_type'] = "车商";
                    } elseif ($item['payment_type'] == 7 || $item['payment_type'] == 8) {
                        $list[$key]['account_id'] = $data['owner_id'];
                        $list[$key]['account_name'] = $data['owner_name'];
                        $list[$key]['account_type'] = "车主";
                    }
                    $list[$key]['order_no'] = $data['order_no'];
                    $list[$key]['car_source_nu'] = $data['sno'];
                } else {
                    $dealer_id = 0;
                    if ($item['payment_type'] == self::$statusGroup['RECHARGE']) { //保证金充值
                        $where = [
                            'use_type' => 1,
                            'collection_id' => $item['id']
                        ];
                        $dealer_id = M("dealer_bail_log")->where($where)->getField("dealer_id");
                    } elseif ($item['payment_type'] == self::$statusGroup['MAINTENANCE']) {
                        $dealer_id = M("dealer_repair_pay_log")
                            ->where(["collection_id" => $item['id']])
                            ->getField("dealer_id");
                    }
                    $list[$key]['account_id'] = $dealer_id;
                    $list[$key]['account_type'] = "车商";
                    $list[$key]['account_name'] = M("car_dealer")
                        ->where(['dealer_id' => $dealer_id])
                        ->getField("contact_person");
                    $list[$key]['order_no'] = "--";
                    $list[$key]['car_source_nu'] = "--";
                }

                if ($item['status'] > 1) {
                    $list[$key]['emp_name'] = empty($item['emp_name']) ? "系统" : $item['emp_name'];
                }
            }
        }
        $data['total'] = $total;
        $data['list'] = $list;
        return $data;
    }

    /**
     * 获取拍单号，车辆编号
     * @param $id
     * @return array
     */
    public static function getOrderInfoById($id)
    {
        $prefix = C("DB_PREFIX");
        $where = ['oc.collection_id' => $id];
        $cols = "oc.collection_id,o.order_id,o.order_no,o.success_dealer_id,o.is_other_channel_deal,
            cd.contact_person as dealer_name,c.sno,po.purchase_order_nu";
        $data = M('order_collections')->alias("oc")->field($cols)
            ->join($prefix . "order as o ON oc.order_id=o.order_id")
            ->join($prefix . "cars as  c ON o.car_id=c.car_id")
            ->join("LEFT JOIN ". $prefix . "car_dealer as cd ON o.success_dealer_id=cd.dealer_id")
            ->join("LEFT JOIN " . $prefix . "purchase_order as po ON c.sid=po.sid")
            ->where($where)->find();
        return $data;
    }

    /**
     * 获取变更单信息
     * @param $id
     * @return array
     */
    public static function getChangeInfoById($id)
    {
        $prefix = C("DB_PREFIX");
        $where = ['chc.collection_id' => $id];
        $cols = "chc.collection_id,ml.modify_no,o.order_no,o.success_dealer_id,cd.contact_person as dealer_name,
            c.owner_id,co.seller_name as owner_name,c.sno,po.purchase_order_nu";
        $data = M('change_collection')->alias("chc")->field($cols)
            ->join($prefix . "modify_list as ml ON chc.change_id=ml.mid")
            ->join($prefix . "purchase_order as po ON ml.po_id=po.id")
            ->join($prefix . "order as o ON ml.order_id=o.order_id")
            ->join($prefix . "car_dealer as cd ON o.success_dealer_id=cd.dealer_id")
            ->join($prefix . "cars as  c ON o.car_id=c.car_id")
            ->join($prefix . "car_owner as  co ON c.owner_id=co.owner_id")
            ->where($where)->find();
        return $data;
    }

    /**
     * 获取退车车辆信息
     * @param $collection_id
     * @param int $isDefault
     * @return mixed
     */
    public static function getRefundCarInfoByCollectionId($collection_id, $isDefault = 0)
    {
        $map = [];
        if ($isDefault == 0) {
            $map['rc.collection_id'] = $collection_id;
        } else {
            $map['rc.collection_id_car'] = $collection_id;
        }
        $prefix = C("DB_PREFIX");
        $field = "c.sno,o.order_no,po.purchase_order_nu,c.owner_id,co.seller_name as owner_name";
        $data = M("refund_car")->alias("rc")->field($field)
            ->join($prefix . "cars AS c ON rc.car_id = c.car_id")
            ->join($prefix . "car_owner AS co ON c.owner_id=co.owner_id")
            ->join($prefix . "order AS o ON c.car_id=o.car_id")
            ->join($prefix . "purchase_order as po ON c.sid=po.sid")
            ->where($map)
            ->find();
        return $data;
    }

    /**
     * 通过id获收款信息
     * @param $id
     * @return mixed
     */
    public static function getInfoById($id)
    {
        return M("collection")->where(['id' => $id])->find();
    }

    /**
     * 是否有未收款的收款单
     * @param $ids
     * @return bool
     */
    public static function checkStatusByIds($ids)
    {
        if (!is_array($ids)) return false;
        $map = [];
        $map['id'] = ['in', $ids];
        $map['status'] = 0; //未付款
        $list = M("collection")->where($map)->select();
        if (!empty($list)) {
            return false;
        }
        return true;
    }


    /**
     * 确认收款
     * @param array $data
     * @return boolean
     */
    public function confirmCollection($data)
    {
        $collectionData = [
            'emp_id' => $data['emp_id'],
            'emp_name' => $data['emp_name'],
            'poundage' => $data['poundage'],
            'status' => $data['status'],
            'update_time' => $data['update_time'],
        ];
        M()->startTrans();
        //更新收款信息
        $resCo = $this->update($collectionData);
        if (!$resCo) {
            M()->rollback();
            Log::record("确认收款，更新收款信息失败，收款ID： [ {$this->collection_id} ] ");
            return false;
        }
        $res = true;
        if (in_array($data['payment_type'], [1, 3])) {
            //拍单处理
            $res = $this->orderConfirm($data);
        } elseif ($data['refer'] == 0 && in_array($data['payment_type'], [6, 7, 8, 10])) {
            //变更单处理
            $res = $this->changeOrderConfirm();
        }
        if (!$res) {
            M()->rollback();
            return false;
        }
        //事务提交
        M()->commit();
        //记录操作日志
        SystemLog::add([
            'emp_id' => $data['emp_id'],
            'order_id' => $this->collection_id,
            'car_id' => 0,
            'owner_id' => 0,
            'action' => '确认收款'
        ]);
        return true;
    }

    /**
     * 拍单确认
     * @param $data
     * @return bool
     */
    public function orderConfirm($data)
    {
        //获取拍单信息
        $orderId = M("order_collections")->where(['collection_id' => $this->collection_id])->getField("order_id");
        //添加验车信息
        $o = new AuOrder($orderId);
        $orderInfo = $o->detail();
        $c = new Car($orderInfo['car_id']);
        $carInfo = $c->detail();
        if (empty($orderInfo)) {
            Log::record("确认收款,拍单信息为空");
            return false;
        }
        $orderData = array();
        $orderData['dealer_pay_status'] = 3;
        if ($orderInfo['is_other_channel_deal'] == 1) { //其他渠道成交
            $orderData['status'] = 9;
            $transferLog = [];
            $transferLog['order_id'] = $orderId;
            $transferLog['sid'] = $carInfo['sid'];
            \AuctionBack\Logic\TransferLogic::addTransferLog($transferLog);
        } else {
            $carCheckInfo = CarCheck::detail_by_order_id($orderInfo['order_id']);
            if (empty($carCheckInfo)) {
                $orderData['check_car_status'] = 1;
                $resCarCheck = $o->add_car_dealer_check();
                if (!$resCarCheck) {
                    Log::record("确认收款，添加验车信息失败，拍单ID [ $orderId ] ");
                    return false;
                }
            } else {
                if ($carCheckInfo['status'] == 2) {
                    $resOrder = $o->update(['status' => 9]);
                    if (!$resOrder) {
                        Log::record("确认付款,更新拍单到过户失败");
                        return false;
                    }
                    //发送消息
                    $uid = $o->get_uid_by_order();
                    $c = new Car($orderInfo['car_id']);
                    $car_name = $c->get_car_name();
                    $content = "【 " . $car_name . " 】拍单编号：" . $orderInfo['order_no'] . "，付款成功。交付顾问正在过户中，敬请关注。";
                    Inbox::sendMessage($uid, '车辆待过户', $content);
                }
            }
        }
        $resOrder = $o->update($orderData); //已付款
        if (!$resOrder) {
            Log::record("确认收款，修改拍单信息失败，拍单ID [ $orderId ] ");
            return false;
        }
        //车款大于2000解冻保证金
        if ($orderInfo['is_other_channel_deal'] == 0 && $data['amount'] >= 2000) {
            $resFree = AssetCenter::unfreeze($orderInfo['success_dealer_id'], $orderId);
            if (!$resFree) {
                Log::record("确认收款，解冻保证金失败，拍单ID [ $orderId ] ");
                return false;
            }
        }
        //更新付款跟踪记录
        M("proceeds_log")->where(['order_id' => $orderId])->save(['pay_time' => $data['update_time']]);
        //记录车辆跟踪日志
        $car_action_data = array(
            'action_name' => "确认收款",
            'emp_id' => $data['emp_id']
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($orderInfo['car_id'], $car_action_data);
        //记录拍品跟踪日志
        $order_action_data = array(
            'action_name' => "确认收款",
            'emp_id' => $data['emp_id']
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($orderId, $order_action_data);
        return true;
    }

    /**
     * @return bool
     */
    public function changeOrderConfirm()
    {
        //获取变更单信息
        $mid = M("change_collection")->where(['collection_id' => $this->collection_id])->getField("change_id");
        $co = new ChangeOrder($mid);
        $changeOrderInfo = $co->detail();
        if (empty($changeOrderInfo)) {
            Log::record("变更单信息不存在");
            return false;
        }
        //变更单回调
        $co->cashierCallback();
        return true;
    }


    /**
     * @param $carSourceNu
     * @return array
     */
    private static function getCollectionIdsByCarSourceNu($carSourceNu)
    {
        $ids = [];
        if (empty($carSourceNu)) {
            return $ids;
        }
        $carIds = Car::getAllCarIdByCarSourceNu($carSourceNu);
        if (empty($carIds)) {
            return $ids;
        }
        $orderIds = AuOrder::getOrderIdsByCarIds($carIds);
        if (empty($orderIds)) {
            return $ids;
        }
        $collectionIds = self::getCollectionIdsByOrderIds($orderIds);
        //获取退车信息
        $carBackInfo = self::getRefundCarInfoByCarSourceNu($carSourceNu);
        if (!empty($carBackInfo)) {
            $collectionIds[] = $carBackInfo['collection_id'];
            $collectionIds[] = $carBackInfo['collection_id_car'];
        }
        $ids = array_filter(array_unique($collectionIds));
        return $ids;
    }

    /**
     * @param $orderIds
     * @return array
     */
    private static function getCollectionIdsByOrderIds($orderIds)
    {
        $collectionIds = [];
        $orderMap = [
            'order_id' => ['in', $orderIds]
        ];
        //车款应收
        $orderCollections = M("order_collections")->field('collection_id')->where($orderMap)->select();
        foreach ($orderCollections as $oc) {
            $collectionIds[] = $oc['collection_id'];
        }
        //变更单
        $changeCollections = M("change_collection")->alias("cc")->field("cc.collection_id")
            ->join(C("DB_PREFIX") . "modify_list AS ml ON cc.change_id=ml.mid")
            ->where(['order_id' => ['in', $orderIds]])
            ->select();
        foreach ($changeCollections as $cc) {
            $collectionIds[] = $cc['collection_id'];
        }
        return $collectionIds;
    }

    /**
     * @param $carSourceNu
     * @param string $table
     * @return mixed
     */
    private function getRefundCarInfoByCarSourceNu($carSourceNu)
    {
        $map = [
            'c.sno' => $carSourceNu,
            'rc.status' => 2
        ];
        $info = M("refund_car")->alias("rc")
            ->join(C("DB_PREFIX") . "cars AS c ON rc.car_id=c.car_id")
            ->where($map)
            ->find();
        return $info;
    }

    /**
     * 根据条件，获取收款单信息
     *
     * @param $condition
     * @return mixed
     */
    public static function getCollectionByCondition($condition)
    {
        return M('collection')->where($condition)->select();
    }
}